package org.beetl.sql.ext.jpa.mapper.builder;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.beetl.sql.clazz.kit.BeanKit;
import org.beetl.sql.core.ExecuteContext;
import org.beetl.sql.core.page.PageRequest;
import org.beetl.sql.mapper.builder.MethodParam;
import org.beetl.sql.mapper.builder.MethodParamsHolder;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;

public class JpaDataParameterParser {
	private Method method;
	private MethodParamsHolder holder = null;
	
    public JpaDataParameterParser(Method method){
        this.method = method;
        this.holder = parse();
    }

    public MethodParamsHolder getHolder() {
        return holder;
    }

    private MethodParamsHolder parse(){
        MethodParamsHolder holder = new MethodParamsHolder();
        List<MethodParam> paras = new ArrayList<>();
        Parameter[] paraConfig = method.getParameters();
        Class[] parasType = method.getParameterTypes();
        Annotation[][] anns = method.getParameterAnnotations();
        
        for (int i = 0; i < paraConfig.length; i++) {
            MethodParam para = new MethodParam();
            Param paramAnno = getParamAnnotation(anns[i]);
//            boolean isRoot = isRoot(anns[i]);
            if(paramAnno!=null){
                para.setName(paramAnno.value());
            }else{
                para.setName(paraConfig[i].getName());
            }
            //TODO 分页可能有问题
            if(Pageable.class.isAssignableFrom(parasType[i])) {
            	holder.setPageRequestIndex(i);
            }

            para.setIndex(i);
            paras.add(para);
        }
        //如果方法还有一个参数
        // TODO 暂不支持 JavaBean类型的参数
//        if(parasType.length==1&&!BeanKit.isBaseDataType(parasType[0])
//                &&!PageRequest.class.isAssignableFrom(parasType[0])){
//            holder.setRootParamIndex(0);
//            paras.get(0).setRoot(true);
//        }
        holder.setParas(paras);
        return holder;
    }


    private boolean isRoot(Annotation[] anns){
        return false;
    }
    
    private Param getParamAnnotation(Annotation[] anns){
        for(Annotation an:anns){
            if(an instanceof Param){
                return (Param)an;
            }
        }
        return null;
    }

}
